<template>
    <view class="page">
        <u-navbar title="收银台" :custom-back="goOrder" :back-icon-color="'#ffffff'" :title-color="'#ffffff'" :background="background"></u-navbar>
        <view class="price-count-down">
            <view class="price">
                <text class="max">￥</text>
                <text class="max" v-if="data.pageType!=2">{{Number(data.order_price).toFixed(2)}}</text>
                <text class="max" v-else>{{Number(data.pay_price).toFixed(2)}}</text>
            </view>
            <!-- <view class="count-down">
                <view class="title">支付剩余时间</view>
                <view class="count">
                    <text class="time">{{hour}}</text>
                    <text class="dot">:</text>
                    <text class="time">{{min}}</text>
                    <text class="dot">:</text>
                    <text class="time">{{sec}}</text>
                </view>
            </view> -->
        </view>
        <view style="height:30rpx;background: #f6f6f6;margin-top:250rpx;"></view>
        <!-- 支付方式列表 -->
        <view class="pay-way">
            <view class="pay-list">
                <view class="list" v-for="(item,index) in data.order_payment" @click="onPayWay(item,index)" :key="index">
                    <view class="pay-type">
                        <image v-if="item.payment_icon" :src="item.payment_icon" mode=""></image>
                        <text>{{item.payment_name}}</text>
                    </view>
                    <view class="check">
                        <text class="iconfont" :class="PayWay === index ? 'icon-checked action' : 'icon-check'"></text>
                    </view>
                </view>
            </view>
        </view>
        <view class="pay-submit">
            <view class="submit" @click="onSubmit">{{PayPirce}}</view>
        </view>

        <!-- 提示框 -->
        <u-modal v-model="show" :title="title" :content="content" show-cancel-button cancel-text="狠心拒绝" cancel-color="#ff2020" confirm-text="继续支付"
            @cancel="cancel" @confirm="confirm"></u-modal>
    </view>
</template>

<script>
import {
    setGoodsOrderToConfirmPay
} from "@/api/my/orderList.js"
import {
    confirmPay,
    paySubmitService
} from "@/api/mall.js"
export default {
    data() {
        return {
            PayWay: 0,
            PayPirce: `微信支付`,
            CountDown: 1000,
            day: 0,
            hour: 0,
            min: 0,
            sec: 0,
            data: {},
            form: {},
            background: {
                // 渐变色
                backgroundImage: 'linear-gradient(to bottom right, #2e996f, #3f99ab)'
            },
            payList: [{
                name: "商品订单发起支付",
                funk: setGoodsOrderToConfirmPay
            },
            {
                name: "商品直接支付",
                funk: confirmPay
            },
            {
                name: "服务详情支付",
                funk: paySubmitService
            },
            ],
            show: false,
            title: '确定放弃支付吗?',
            content: "订单已生成在我的--我的订单里",
        };
    },
    onLoad(query) {
        wx.enableAlertBeforeUnload({
            message: "确定放弃支付吗?",
            success: (res) => {
                console.log("成功：", res);
            },
            fail: (err) => {

            },
        });
        if (query) {
            this.data = JSON.parse(decodeURIComponent(query.dataList))
            console.log(this.data, "this.data this.data this.data ")
            this.form = this.data.order_payment[0]
            // let fun = this.data.pageType == 1 ? setGoodsOrderToConfirmPay : confirmPay
            // fun({
            //     payment_id: this.form.payment_id,
            //     order_no: this.data.order_no
            // }).then((res) => {
            //     console.log(res,11111)
            // })
            // this.data.pageType   1订单发起支付  2商品直接支付  3服务详情  4电影票支付
            console.log(this.data, "this.datathis.datathis.datathis.datathis.data")
        }
        this.CountDownData();
    },
    onUnload: function () {
        let url = this.data.pageType == 3 ? '/pagesA/my/serviceOrders' : '/pagesA/my/myOrderList'
        uni.reLaunch({
            url: url
        })
    },
    methods: {
        /**
         * 返回点击
         */
        onBack() {
            uni.navigateBack();
        },
        /**
         * 支付方式切换点击
         */
        onPayWay(item, index) {
            this.PayWay = index;
            this.form = item
            this.PayPirce = `${item.payment_name}`
        },
        /**
         * 倒计时
         */
        CountDownData() {
            setTimeout(() => {
                this.CountDown--;
                this.day = parseInt(this.CountDown / (24 * 60 * 60))
                this.hour = parseInt(this.CountDown / (60 * 60) % 24);
                this.min = parseInt(this.CountDown / 60 % 60);
                this.sec = parseInt(this.CountDown % 60);
                if (this.CountDown <= 0) {
                    return
                }
                this.CountDownData();
            }, 1000)
        },
        /**
         * 支付点击
         */
        onSubmit() {
            let money = this.data.pageType != 2 ? this.data.order_price : this.data.pay_price
            if (money == 0) {
                this.exchange()
            } else if (money > 0) {
                // #ifndef MP-WEIXIN
                if (this.form.payment_type == "wechat_app") {
                    this.wxPay()
                } else if (this.form.payment_type == "alipay_app") {
                    this.zfbPay()
                }
                // #endif
                // #ifdef MP-WEIXIN
                this.wxMiniPay()
                // #endif
            }
        },
        exchange() {
            this.payList[this.data.pageType - 1].funk({
                payment_id: 0,
                order_no: this.data.order_no
            }).then((res) => {
                console.log(res, "resss")
                if (res.code == 1) {
                    uni.showToast({
                        title: '支付成功',
                        icon: 'none'
                    })
                    setTimeout(() => {
                        uni.reLaunch({
                            url: "/pagesA/mall/payResult?type=success&pageType" + this.data
                                .pageType
                        })
                    }, 500)
                }
            })
        },
        wxPay() {
            // #ifdef APP-PLUS
            uni.getProvider({ //获取应用服务商
                service: 'payment',
                success: res => {
                    console.log(res, "ressss")
                    if (res.providers.indexOf('wxpay')) { //先判断用户是否有微信支付环境（是否安装了微信app）
                        lthis.payList[this.data.pageType - 1].funk({
                            payment_id: this.form.payment_id,
                            order_no: this.data.order_no
                        }).then((res1) => {
                            console.log('查看子订单信息', res1)
                            let data = res1.data.pay_data.wxapppay_data
                            console.log(data, "data")
                            //拿到需要进行微信支付的订单信息，必须严格按照微信支付API所需要的支付信息大小写字段进行编码						
                            let payInfo = {
                                appid: data.appid,
                                noncestr: data.noncestr,
                                package: "Sign=WXPay",
                                partnerid: data.partnerid,
                                prepayid: data.prepay_id,
                                timestamp: data.timestamp,
                                sign: data.sign,
                            }
                            console.log('生成订单', payInfo)
                            uni.requestPayment({
                                provider: 'wxpay',
                                orderInfo: payInfo, //微信订单数据（Object类型）
                                success: res2 => {
                                    console.log(res2, "res2")
                                    uni.showToast({
                                        title: '支付成功',
                                        icon: 'none'
                                    })
                                    setTimeout(() => {
                                        uni.reLaunch({
                                            url: "/pagesA/mall/payResult?type=success&pageType=" +
                                                this.data.pageType
                                        })
                                    }, 500)
                                },
                                fail: err => {
                                    console.log('失败得原因', err)
                                    uni.showToast({
                                        title: '支付失败',
                                        icon: 'none'
                                    })
                                    setTimeout(() => {
                                        uni.reLaunch({
                                            url: "/pagesA/mall/payResult?type=fail&pageType=" +
                                                this.data.pageType
                                        })
                                    }, 500)
                                }
                            });
                        })
                    }
                }
            })
            // #endif
        },
        //支付宝支付
        zfbPay() {
            // #ifdef APP-PLUS
            uni.getProvider({ //获取可用的支付环境
                service: 'payment',
                success: (res) => {
                    if (res.providers.indexOf('alipay')) { //先判断用户是否有微信支付环境（是否安装了微信app）
                        this.payList[this.data.pageType - 1].funk({
                            payment_id: this.form.payment_id,
                            order_no: this.data.order_no
                        }).then((res1) => {
                            console.log(res1.data.pay_data.aliapppay_data,
                                "res1.data.pay_data.aliapppay_data")
                            uni.requestPayment({
                                provider: 'alipay',
                                orderInfo: res1.data.pay_data.aliapppay_data,
                                success: (res2) => {
                                    console.log(res2, "res2res2")
                                    uni.showToast({
                                        title: '支付成功',
                                        icon: 'none'
                                    })
                                    setTimeout(() => {
                                        uni.reLaunch({
                                            url: "/pagesA/mall/payResult?type=success&pageType=" +
                                                this.data.pageType
                                        })
                                    }, 500)
                                },
                                fail: (err) => {
                                    console.log('失败得原因', err)
                                    uni.showToast({
                                        title: '支付失败',
                                        icon: 'none'
                                    })
                                    setTimeout(() => {
                                        uni.reLaunch({
                                            url: "/pagesA/mall/payResult?type=fail&pageType=" +
                                                this.data.pageType
                                        })
                                    }, 500)
                                }
                            });
                        })
                    } else {
                        uni.showToast({
                            title: '获取支付宝通道失败，请检查您的支付宝是否正常启用',
                            icon: 'none'
                        })
                    }
                }
            });
            // #endif
        },
        wxMiniPay() {
            // let fun;
            // if (this.data.pageType == 3) {
            //     fun = paySubmitService
            // } else {
            //     fun = this.data.pageType == 1 ? setGoodsOrderToConfirmPay : confirmPay
            // }
            this.payList[this.data.pageType - 1].funk({
                payment_id: this.form.payment_id,
                order_no: this.data.order_no
            }).then((res) => {
                let data = res.data.pay_data.minipay_data
                wx.requestPayment({
                    timeStamp: data.timeStamp,
                    nonceStr: data.nonceStr,
                    package: data.package,
                    signType: 'MD5',
                    paySign: data.paySign,
                    success: (res) => {
                        if (res.errMsg == "requestPayment:ok") {
                            uni.showToast({
                                title: '支付成功',
                                icon: 'none'
                            })
                            setTimeout(() => {
                                uni.reLaunch({
                                    url: "/pagesA/mall/payResult?type=success&pageType=" +
                                        this.data.pageType
                                })
                            }, 500)
                        }
                    },
                    fail: (error) => {
                        if (error.errMsg == "requestPayment:fail cancel") {
                            uni.showToast({
                                title: '支付失败',
                                icon: 'none'
                            })
                            setTimeout(() => {
                                uni.reLaunch({
                                    url: "/pagesA/mall/payResult?type=fail&pageType=" +
                                        this.data.pageType
                                })
                            }, 500)
                        }
                    }
                })
            })
        },
        goOrder() {
            if (this.data.pageType != 2) {
                uni.navigateBack();
            }
            this.show = true
            // let url = this.data.pageType == 3 ? '/pagesA/my/serviceOrders' : '/pagesA/my/myOrderList'
            // uni.reLaunch({
            //     url: url
            // })
        },
        cancel() {
            this.show = false
            let url = this.data.pageType == 3 ? '/pagesA/my/serviceOrders' : '/pagesA/my/myOrderList'
            uni.reLaunch({
                url: url
            })
        },
        confirm() {
            this.show = false
        },
    }
}
</script>

<style scoped lang="scss">
.page {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #fff;
  // background-color: #f6f6f6;
}

/* 金额倒计时 */
.price-count-down {
  position: absolute;
  left: 0;
  top: 100rpx;
  /* #ifdef APP-PLUS || MP-WEIXIN */
  top: calc(100rpx + var(--status-bar-height));
  /* #endif */
  width: 100%;
  height: 250rpx;
  background-color: #ffffff;
  padding-top: 30rpx;

  .price {
    padding: 30rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;

    // height: 80rpx;
    text {
      color: #ff2020;
      font-weight: bold;
    }

    .min {
      font-size: 32rpx;
    }

    .max {
      font-size: 52rpx;
    }
  }

  .count-down {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 60rpx;

    .title {
      font-size: 24rpx;
      color: #222222;
    }

    .count {
      display: flex;
      align-items: center;
      margin-left: 20rpx;

      .time {
        padding: 4rpx 4rpx;
        background-color: #eeeeee;
        font-size: 24rpx;
        color: #222222;
        border-radius: 2rpx;
      }

      .dot {
        margin: 0 10rpx;
        font-size: 24rpx;
        color: #222222;
      }
    }
  }
}

/* 支付方式 */
.pay-way {
  width: 100%;
  background-color: #ffffff;
  margin-top: 30rpx;

  .pay-list {
    padding: 0 4%;

    .list {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      height: 100rpx;
      border-bottom: 2rpx solid #f6f6f6;

      .pay-type {
        display: flex;
        align-items: center;

        image {
          width: 40rpx;
          height: 40rpx;
        }

        text {
          font-size: 28rpx;
          color: #222222;
          margin-left: 20rpx;
        }
      }

      .check {
        display: flex;
        align-items: center;

        text {
          font-size: 42rpx;
          color: #c0c0c0;
        }

        .action {
          color: $base;
        }
      }
    }
  }
}

/* 支付提交 */
.pay-submit {
  // position: absolute;
  // left: 0;
  // bottom: 0;
  margin-top: 200rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 140rpx;
  background-color: #ffffff;

  .submit {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 90%;
    height: 70%;
    background-color: $base;
    color: #ffffff;
    border-radius: 10rpx;
    font-size: 42rpx;
  }
}
</style>